package com.hanxiaozhang.io.sockettcp;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.Socket;

/**
 * 〈一句话功能简述〉<br>
 * 〈〉
 *
 * @author hanxinghua
 * @create 2023/6/9
 * @since 1.0.0
 */
public class TcpUtil {

    /**
     * 接受消息
     *
     * @param socket
     * @return
     * @throws IOException
     */
    public static String receiveMsg(Socket socket) throws IOException {
        StringBuilder inMessage = new StringBuilder();
        BufferedInputStream in = new BufferedInputStream(socket.getInputStream());
        while (true) {
            int c = in.read();
            if (c == -1 || c == '\n') {
                break;
            }
            inMessage.append((char) c);
        }
        return inMessage.toString();
    }

    /**
     * 发送消息
     *
     * @param socket
     * @param req
     * @throws IOException
     */
    public static void sendMsg(Socket socket, String req) throws IOException {
        req = req + "\n";
        OutputStream out = new BufferedOutputStream(socket.getOutputStream());
        out.write(req.getBytes());
        // 不能忘记 flush 方法的调用
        out.flush();
    }
}
